package algorithm;

import lombok.Data;
import org.junit.Test;

import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;

/**
 * @author bigOrang
 * @date 2021/9/12
 * xxx
 */
public class QueueToStack {

    @Test
    public void test() throws InterruptedException {

        MyStack myStack = new MyStack();

        for (int i = 0; i < 1000; i++) {
            try {
                myStack.put(i);
                System.out.println("put " + i);
                if (i % 3 == 0) {
                    System.out.println("poll" + myStack.poll());
                }

            } catch (Exception e) {
                e.printStackTrace();
                Object obj = null;
                while ((obj = myStack.poll()) != null) {
                    System.out.println(obj);
                }
                break;
            }

        }

    }


}

@Data
class MyStack {

    static ArrayBlockingQueue<Object> queue1 = new ArrayBlockingQueue<>(10);
    static ArrayBlockingQueue<Object> queue2 = new ArrayBlockingQueue<>(10);

    private Object i;


    public void put(Object v) throws InterruptedException {
        if (queue1.size() + queue2.size() >= 10) {
            throw new RuntimeException("full");
        }

        if (queue1.isEmpty() && queue2.isEmpty()) {
            queue1.put(v);
        } else if (!queue1.isEmpty()) {
            Object value;
            queue2.put(v);
            while ((value = queue1.poll()) != null) {
                queue2.put(value);
            }
        } else {
            Object value;
            queue1.put(v);
            while ((value = queue2.poll()) != null) {
                queue1.put(value);
            }
        }
    }

    public Object poll() {
        if (!queue1.isEmpty()) {
            return queue1.poll();
        }
        if (!queue2.isEmpty()) {
            return queue2.poll();
        }
        return null;
    }


}
